# 使用SQLAlchemy ORM 连接mysql数据库
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# 数据库连接字符串
SQLALCHEMY_DATABASE_URL = 'mysql+pymysql://root:testroot@192.168.1.128/py_test?charset=utf8'

# 创建引擎 echo=True 会打印出所有的SQL语句
engine = create_engine(SQLALCHEMY_DATABASE_URL, echo=False)

# 创建 Session 工厂 autocommit=True 会自动提交事务 autoflush=True 会自动刷新数据
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 基类，用于定义模型
Base = declarative_base()


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def init_db():
    print(Base.metadata.tables.keys())
    Base.metadata.create_all(bind=engine)